import pyzbar.pyzbar as pyzbar
import base64
import subprocess
import tkinter as tk
from tkinter.messagebox import *
import matplotlib
import os
import shutil
import threading
from tkinter import *
from tkinter import ttk
from tkinter.ttk import Label
import cv2
import time
from PIL import Image
from PIL import ImageTk
import tkinter
import tkinter.messagebox
import qrcode
from tkinter import filedialog
import math
import imageio

class Bottun_spe:
    def __init__(self, where, text, width, height, com=None, row=None, cod=None):
        def on_enter(e):
            myButton['background'] = '#EDF6FB'
            myButton['fg'] = 'blue'

        def on_leave(e):
            myButton['background'] = '#FAFAFA'
            myButton['fg'] = 'black'

        self.data = []
        myButton = tk.Button(where, width=width, height=height, bg='#FAFAFA', relief=FLAT, text=text, command=com)
        myButton.bind("<Enter>", on_enter)
        myButton.bind("<Leave>", on_leave)
        myButton.grid(row=row, column=cod)

def delate(i):
    os.remove(i)

def del_file():  # 删除路径下的所有文件
    path_data = r"pic"
    for i in os.listdir(path_data):
        file_data = path_data + "/" + i
        if os.path.isfile(file_data):
            os.remove(file_data)

    path_data = r"result"
    for i in os.listdir(path_data):
        file_data = path_data + "/" + i
        if os.path.isfile(file_data):
            os.remove(file_data)

    path_data = r"temp"
    for i in os.listdir(path_data):
        file_data = path_data + "/" + i
        if os.path.isfile(file_data):
            os.remove(file_data)

    with open("word/生成.txt", 'w+') as f:
        txt = "  等待生成二维码"
        f.write(txt)



def create_base64(struct_pic):  # 加密模块
    file_path = struct_pic[1]
    try:
        file = open(file_path, 'rb')
        print(file.name)
    except Exception:
        print("非法退出")
    with open("word/生成.txt", 'w+') as f:
        f.write("当前生成二维码的文件是：" + file_path + "\n二维码版本是：" + str(struct_pic[2]) + "\n二维码纠错速率是：" + str(struct_pic[3]))
    file_content = file.read()
    file_content = base64.b64encode(file_content).decode()
    number = 1
    del_file()
    maxDataBitsArray = [0, 152, 272, 440, 640, 864, 1088, 1248, 1552, 1856, 2192, 2592, 2960, 3424, 3688, 4184, 4712, 5176, 5768, 6360, 6888, 7456, 8048, 8752, 9392, 10208, 10960, 11744, 12248, 13048, 13880, 14744, 15640, 16568, 17528, 18448, 19472, 20528, 21616, 22496, 23648]
    ver_number = int(maxDataBitsArray[int(struct_pic[2])]/8 - 25)
    print(ver_number)
    while number <= math.ceil(len(file_content) / ver_number):
        print(number)
        print(len(str(number).zfill(8) + str(math.ceil(len(file_content) / ver_number)).zfill(8) + str(file_content[(number-1)*ver_number : number*ver_number])))
        print(math.ceil(len(file_content) / ver_number))
        make_qrcode(struct_pic, str(number).zfill(8) + str(math.ceil(len(file_content) / ver_number)).zfill(8) + str(file_content[(number-1)*ver_number : number*ver_number]),
                    "pic/Test" + str(number) + ".png")
        number = number + 1
    image_list= []
    frames = []
    i = 1
    num = 0
    max = int(struct_pic[4])
    for row in range(max):
        image_list.append([])
        columns = []
        i = 1
        while i<=number-1:
            if i%max== row:
                columns.append(i)
            i=i+1
        for column in columns:
            image_list[row].append('pic/Test' + str(column) + '.png')
    print(image_list)
    print("List")
    num = 0
    while num < max:
        frames.append([])
        for image_name in image_list[num]:
            frames[num].append(imageio.imread(image_name))
        num = num + 1
    print("image")
    print(frames)
    num = 0
    while num < max:
        imageio.mimsave('pic/new'+str(num+1)+'.gif', frames[num], 'GIF', duration=float(struct_pic[3]))
        num = num + 1
        print(num)
    showinfo("提示", "生成成功")

    with open("word/生成.txt", 'w+') as f:
        txt = "  生成的文件 : "+str(struct_pic[1])+"\n  二维码大小版本 : "+str(struct_pic[2])+"\n  二维码循环速率 : "+str(struct_pic[3])
        f.write(txt)


def make_qrcode(struct_pic, data=None, name="", **kwargs):  # 创建二维码
    qr = qrcode.QRCode(
        version=int(struct_pic[2]),
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=2,
    )
    qr.add_data(data)
    qr.make()
    img = qr.make_image()
    img.save(name)

class MyLabel(Label):  # 播放GIF
    def __init__(self, master, filename='pic.gif', number=1):
        if number == 1:
            size = 500
        elif number == 2:
            size = 400
        elif number == 3:
            size = 280
        elif number == 6:
            size = 250
        if os.path.exists(filename):
            im = Image.open(filename)
        else:
            im = Image.open('pic.gif')
        seq = []
        try:
            while 1:
                seq.append(im.copy())
                im.seek(len(seq))
        except EOFError:
            pass  # we're done

        try:
            self.delay = im.info['duration']
        except KeyError:
            self.delay = 100

        print(self.delay)
        first = seq[0].convert('RGBA')
        first = first.resize((size, size), Image.ANTIALIAS)
        self.frames = [ImageTk.PhotoImage(first)]

        Label.__init__(self, master)

        temp = seq[0]
        for image in seq[1:]:
            temp.paste(image)
            frame = temp.convert('RGBA')
            frame = frame.resize((size, size), Image.ANTIALIAS)
            self.frames.append(ImageTk.PhotoImage(frame))

        self.idx = 0
        global ticks
        ticks = time.ctime()
        print(ticks)
        self.cancel = self.after(self.delay, self.play)  # after循环

    def play(self):
        self.config(image=self.frames[self.idx])
        self.idx += 1
        global ticks
        if self.idx == len(self.frames):
            self.idx = 0
        self.cancel = self.after(self.delay, self.play)

class basedesk():
    def __init__(self, master):
        self.root = master
        self.root.config()
        self.root.title('二维码传输')

        self.root.geometry('1100x629')
        self.root.minsize(1100, 629)  # 最小尺寸
        self.root.maxsize(1100, 629)

        del_file()

        menubar = tk.Menu(self.root)
        filemenu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label='生成', menu=filemenu)
        filemenu.add_command(label='打开')
        filemenu.add_separator()
        filemenu.add_command(label='Exit')
        editmenu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label='识别', menu=editmenu)
        editmenu.add_command(label='设置')
        tk.Menu(filemenu)
        helpmenu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label='帮助文档')
        helpmenu.add_command(label='设置')
        tk.Menu(helpmenu)
        self.root.config(menu=menubar, bg='#FAFAFA')
        global flag
        flag = 0
        initface(self.root)


class initface():
    def __init__(self, master):
        def but0():
            global flag
            flag = 0
            self.flash()

        def but1():
            global flag
            flag = 1
            self.flash()

        def but2():
            global flag
            flag = 2
            self.flash()

        def but3():
            global flag
            flag = 3
            self.flash()

        def but4():
            os.system("start explorer test")

        def search(ev=None):
            self.serch(u.get())

        def entry_del(ev=None):
            global flag
            if(flag == 1):
                ent.delete(0, END)
                flag = 0

        self.master = master
        self.master.config()
        # 基准界面initface
        self.initface_left = tk.Frame(self.master, )
        self.initface_left.place(x=0.5, y=0.5)
        Bottun_spe(self.initface_left, '首页', 9, 4, None, 2, 1)
        Bottun_spe(self.initface_left, '传输', 9, 4, self.change, 3, 1)
        self.initface_mid = tk.Frame(self.master, )
        self.initface_mid.place(x=80, y=0.5)
        Bottun_spe(self.initface_mid, '  全部文件  :', 20, 2, but0, 1, 1)
        Bottun_spe(self.initface_mid, '  图片', 20, 2, but1, 2, 1)
        Bottun_spe(self.initface_mid, '  文档', 20, 2, but2, 3, 1)
        Bottun_spe(self.initface_mid, '  其他', 20, 2, but3, 4, 1)

        self.initface_right = tk.Frame(self.master, )
        self.initface_right.place(x=230, y=0.5)

        Bottun_spe(self.initface_right, '  上传', 10, 2, self.load, 1, 1)
        Bottun_spe(self.initface_right, '刷新', 10, 2, self.flash, 2, 5)
        Bottun_spe(self.initface_right, '  打开目录', 10, 2, but4, 1, 2)
        global u
        tk.Label(self.initface_right, text='工作目录>').grid(row=2, column=1)
        tk.Label(self.initface_right,
                 text='                                                                                                                               |').grid(
            row=2, column=3)
        global flag
        flag = 0
        u = StringVar()
        u.set("搜索")
        ent = tk.Entry(self.initface_right, textvariable=u)
        ent.grid(row=2, column=4)
        ent.bind("<Return>", search)
        ent.bind("<Button-1>", entry_del)
        self.initface_right_button = Frame(self.master, width=300, height=300)
        self.initface_right_button.place(x=230, y=110)
        self.flash()

    def serch(self, txt):
        number = 0
        self.initface_right_button.destroy()
        path_data = r"test"
        self.initface_right_button = Frame(self.master, width=600, height=600)
        self.initface_right_button.place(x=240, y=80)
        yscrollbar = tk.Scrollbar(self.initface_right_button)
        yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        theLB = Listbox(self.initface_right_button, yscrollcommand=yscrollbar.set, width=120, height=28)
        theLB.pack()
        yscrollbar.config(command=theLB.yview)
        for i in os.listdir(path_data):
            number = number + 1
            if i.find(txt) > 0:
                theLB.insert(END, i)

    def but(self, struct_picture):
        create_base64(struct_picture)
        self.change(struct_picture[4])

    def flash(self):
        def Call1On(event):
            os.startfile("test\\" + theLB.get(theLB.curselection()))

        def Call2On(event):
            def show_data_1(*args):
                struct_picture[2] = com_qrcode_data.get()

            def show_data_2(*args):
                struct_picture[3] = com_qrcode_mistake.get()


            def show_data_3(*args):
                struct_picture[4] = com_qrcode_number.get()

            new = tk.Tk()
            new.title("选择")
            struct_picture = [[]]
            xVariable_2 = tk.StringVar()
            tk.Label(new, text='二维码大小：', font=('Arial', 12), width=10, height=2).grid(row=1, column=1)
            com_qrcode_data = ttk.Combobox(new, textvariable=xVariable_2)
            com_qrcode_data["value"] = ("10", "15", "14", "23", "18")
            com_qrcode_data.current(0)
            com_qrcode_data.grid(row=1, column=2)
            com_qrcode_data.bind("<<ComboboxSelected>>", show_data_1)

            xVariable_3 = tk.StringVar()
            tk.Label(new, text='二维码循环速率：', font=('Arial', 12), width=15, height=2).grid(row=2, column=1)
            com_qrcode_mistake = ttk.Combobox(new, textvariable=xVariable_3)
            com_qrcode_mistake["value"] = (0.02, 0.05, 0.08, 0.1)
            com_qrcode_mistake.current(0)
            com_qrcode_mistake.grid(row=2, column=2)
            com_qrcode_mistake.bind("<<ComboboxSelected>>", show_data_2)

            xVariable_4 = tk.StringVar()
            tk.Label(new, text='二维码个数：', font=('Arial', 12), width=15, height=2).grid(row=3, column=1)
            com_qrcode_number = ttk.Combobox(new, textvariable=xVariable_4)
            com_qrcode_number["value"] = (1, 2, 3, 4, 6)
            com_qrcode_number.current(0)
            com_qrcode_number.grid(row=3, column=2)
            com_qrcode_number.bind("<<ComboboxSelected>>", show_data_3)

            struct_picture.append("test/" + theLB.get(theLB.curselection()))
            struct_picture.append(com_qrcode_data.get())
            struct_picture.append(com_qrcode_mistake.get())
            struct_picture.append(com_qrcode_number.get())
            tk.Button(new, text="确认", command=lambda: self.but(struct_picture)).grid(row=3, column=3)
            new.mainloop()

        def Call3On(event):
            delate("test/" + theLB.get(theLB.curselection()))
            showinfo("提示", "删除成功")
            self.flash()

        def CallOn(event):
            menu = Menu(theLB, tearoff=0)
            menu.add_command(label="打开", command=lambda: Call1On(event))
            menu.add_separator()
            menu.add_command(label="生成", command=lambda: Call2On(event))
            menu.add_separator()
            menu.add_command(label="删除", command=lambda: Call3On(event))
            menu.post(event.x_root, event.y_root)

        global flag
        self.initface_right_button.destroy()
        path_data = r"test"
        self.initface_right_button = Frame(self.master, width=600, height=600)
        self.initface_right_button.place(x=240, y=80)
        yscrollbar = tk.Scrollbar(self.initface_right_button)
        yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        theLB = Listbox(self.initface_right_button, bg="#FAFAFA", yscrollcommand=yscrollbar.set, width=120, height=28)
        theLB.pack()
        yscrollbar.config(command=theLB.yview)
        theLB.bind('<Double-Button-1>', CallOn)

        for i in os.listdir(path_data):
            file = os.path.splitext(i)
            filename, type = file
            if flag == 0:
                theLB.insert(END, i)
            elif flag == 1:
                if (type == '.jpg') | (type == '.png') | (type == '.jpeg'):
                    theLB.insert(END, i)
            elif flag == 2:
                if (type == '.txt') | (type == '.pdf'):
                    theLB.insert(END, i)
            elif flag == 3:
                if (type != '.txt') & (type != '.pdf') & (type != '.jpg') & (type != '.png') & (type != '.jpeg'):
                    theLB.insert(END, i)

    def load(self):
        try:
            old_path = tk.filedialog.askopenfilename()
            print(old_path)
            shutil.copy(old_path, os.getcwd() + "/test")
            showinfo("提示", "上传成功")
            self.flash()
        except IOError:
            print("Error: 没有找到文件或读取文件失败")

    def change(self, number=1):
        self.initface_left.destroy()
        self.initface_mid.destroy()
        self.initface_right.destroy()
        self.initface_right_button.destroy()
        face1(self.master, number)


class face1():
    def __init__(self, master, number=1):
        number = int(number)
        self.master = master
        self.face1_left = tk.Frame(self.master, )
        self.face1_left.place(x=0.5, y=0.5)
        Bottun_spe(self.face1_left, '首页', 9, 4, lambda : self.desktop(number), 2, 1)
        Bottun_spe(self.face1_left, '传输', 9, 4, None, 3, 1)
        self.face1_mid = tk.Frame(self.master, )
        self.face1_mid.place(x=80, y=0.5)

        Bottun_spe(self.face1_mid, '  功能  :', 20, 2, None, 1, 1)
        Bottun_spe(self.face1_mid, '生成', 20, 2, None, 2, 1)
        Bottun_spe(self.face1_mid, '识别', 20, 2, lambda : self.face2_transfer(number), 3, 1)

        self.face1_right_top = tk.Frame(self.master, )
        self.face1_right_top.place(x=260, y=0.5)
        tk.Label(self.face1_right_top, text='二维码识别----', width=30, height=1).pack()
        anim = MyLabel(self.face1_right_top, 'pic/new1.gif', number)
        anim.pack(side=TOP)

        if number == 2:
            self.face1_right_top_2 = tk.Frame(self.master, )
            self.face1_right_top_2.place(x=664, y=22)
            anim = MyLabel(self.face1_right_top_2, 'pic/new2.gif', number)
            anim.pack(side=TOP)

        if number == 3:
            self.face1_right_top_2 = tk.Frame(self.master, )
            self.face1_right_top_2.place(x=544, y=22)
            anim = MyLabel(self.face1_right_top_2, 'pic/new2.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_3 = tk.Frame(self.master, )
            self.face1_right_top_3.place(x=820, y=22)
            anim = MyLabel(self.face1_right_top_3, 'pic/new3.gif', number)
            anim.pack(side=TOP)

        if number == 4:
            self.face1_right_top_2 = tk.Frame(self.master, )
            self.face1_right_top_2.place(x=544, y=22)
            anim = MyLabel(self.face1_right_top_2, 'pic/new2.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_4 = tk.Frame(self.master, )
            self.face1_right_top_4.place(x=260, y=320)
            anim = MyLabel(self.face1_right_top_4, 'pic/new4.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_5 = tk.Frame(self.master, )
            self.face1_right_top_5.place(x=544, y=320)
            anim = MyLabel(self.face1_right_top_5, 'pic/new5.gif', number)
            anim.pack(side=TOP)

        if number == 6:
            self.face1_right_top_2 = tk.Frame(self.master, )
            self.face1_right_top_2.place(x=544, y=22)
            anim = MyLabel(self.face1_right_top_2, 'pic/new2.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_3 = tk.Frame(self.master, )
            self.face1_right_top_3.place(x=800, y=22)
            anim = MyLabel(self.face1_right_top_3, 'pic/new3.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_4 = tk.Frame(self.master, )
            self.face1_right_top_4.place(x=260, y=320)
            anim = MyLabel(self.face1_right_top_4, 'pic/new4.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_5 = tk.Frame(self.master, )
            self.face1_right_top_5.place(x=544, y=320)
            anim = MyLabel(self.face1_right_top_5, 'pic/new5.gif', number)
            anim.pack(side=TOP)
            self.face1_right_top_6 = tk.Frame(self.master, )
            self.face1_right_top_6.place(x=800, y=320)
            anim = MyLabel(self.face1_right_top_6, 'pic/new6.gif', number)
            anim.pack(side=TOP)

        self.face1_right_button = tk.Frame(self.master, )
        self.face1_right_button.place(x=240, y=550)

    def desktop(self, number=1):
        self.face1_left.destroy()
        self.face1_mid.destroy()
        self.face1_right_top.destroy()
        self.face1_right_button.destroy()
        if number >=2:
            self.face1_right_top_2.destroy()
        if number >=3:
            self.face1_right_top_3.destroy()
        if number >=4:
            self.face1_right_top_4.destroy()
        if number >=6:
            self.face1_right_top_5.destroy()
            self.face1_right_top_6.destroy()

        initface(self.master)

    def face2_transfer(self, number=1):
        self.face1_left.destroy()
        self.face1_mid.destroy()
        self.face1_right_top.destroy()
        self.face1_right_button.destroy()
        if number >=2:
            self.face1_right_top_2.destroy()
        if number >=3:
            self.face1_right_top_3.destroy()
        if number >=4:
            self.face1_right_top_4.destroy()
        if number >=6:
            self.face1_right_top_5.destroy()
            self.face1_right_top_6.destroy()
        face2(self.master)

class face2():
    def __init__(self, master):
        self.master = master
        self.master.config()
        self.face2_left = tk.Frame(self.master, )
        self.face2_left.place(x=0.5, y=0.5)
        self.flag = True

        Bottun_spe(self.face2_left, '首页', 9, 4, self.desktop, 2, 1)
        Bottun_spe(self.face2_left, '传输', 9, 4, None, 3, 1)
        self.face2_mid = tk.Frame(self.master, )
        self.face2_mid.place(x=80, y=0.5)

        Bottun_spe(self.face2_mid, '功能:', 20, 2, None, 1, 1)
        Bottun_spe(self.face2_mid, '生成', 20, 2, self.face1_transfer, 2, 1)
        Bottun_spe(self.face2_mid, '识别', 20, 2, None, 3, 1)

        self.face2_right = tk.Frame(self.master, )
        self.face2_right.place(x=240, y=0.5)
        tk.Label(self.face2_right, text='二维码识别----', width=30, height=1).pack()

        self.face2_right_button = tk.Frame(self.master, )
        self.face2_right_button.place(x=240, y=485)
        tk.Button(self.face2_right, text="视频传输", width=20, height=3, command=self.select_video_load).pack()
        tk.Button(self.face2_right, text="帧传输", width=20, height=3, command=self.select_video).pack()

    def select_video(self):
        self.face2_right.destroy()
        self.face2_right = tk.Frame(self.master, )
        self.face2_right.place(x=240, y=0.5)
        tk.Label(self.face2_right, text='二维码识别----', width=30, height=1).pack()
        canvas = tk.Canvas(self.face2_right, height=500, width=500)
        canvas.pack()
        self.face2_right_button = tk.Frame(self.master, )
        self.face2_right_button.place(x=240, y=485)
        yscrollbar = tk.Scrollbar(self.face2_right_button)
        yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        theLB = Listbox(self.face2_right_button, yscrollcommand=yscrollbar.set, width=80, height=5)
        theLB.pack()
        yscrollbar.config(command=theLB.yview)
        self.video_demo(canvas, theLB)

    def select_video_load(self):
        self.face2_right.destroy()
        self.face2_right = tk.Frame(self.master, )
        self.face2_right.place(x=240, y=0.5)
        tk.Label(self.face2_right, text='二维码识别----', width=30, height=1).pack()
        canvas = tk.Canvas(self.face2_right, height=500, width=500)
        canvas.pack()
        self.face2_right_button = tk.Frame(self.master, )
        self.face2_right_button.place(x=240, y=485)
        yscrollbar = tk.Scrollbar(self.face2_right_button)
        yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        theLB = Listbox(self.face2_right_button, yscrollcommand=yscrollbar.set, width=80, height=5)
        theLB.pack()
        yscrollbar.config(command=theLB.yview)
        self.video_demo_load(canvas)
        tk.Button(self.face2_right_button, text="开始识别", command=lambda:self.load(canvas, theLB)).pack()
    def load(self, canvas, theLB):
        def decodeDisplay(img):
            barcodes = pyzbar.decode(img)
            global number
            for barcode in barcodes:
                barcodeData = barcode.data.decode("gb18030")
                try:
                    i = int(barcodeData[:8])
                except ValueError:
                    return img
                try:
                    max = int(barcodeData[8:16])
                except ValueError:
                    return img
                ll = ''
                if not os.path.exists("temp/result" + str(i) + ".txt"):
                    barcodeData = barcodeData[16:]
                    with open("temp/result" + str(i) + ".txt", "w+") as f:
                        f.write(barcodeData)
                        number = number + 1
                        global sat
                        if max > 10:
                            if number % math.ceil(max/50) == 1:
                                sat = time.time()
                            elif number % math.ceil(max/50) == 0:
                                ent = time.time()
                                theLB.insert(END, "识别进度"+str("%.1f" % (number/max))+" 时间： " + "%.2f" % (round(ent-sat, 2))+"s")
                                print("%.2f" % (round(ent-sat, 2)))
                                theLB.see(END)
                            #print("%.2f" % (((max / 50) * 0.34 * 0.75) / round(ent - sat, 2)))
                            #print("识别进度"+str("%.3f" % (number/max))+" 速率： " + "%.2f" % (((max/50)*0.34)/round(ent-sat, 2))+"KB/s")
                    if number == max:
                        j = 1
                        while j <= number:
                            with open("temp/result" + str(j) + ".txt", "r+") as f:
                                txt = f.read()
                            ll = ll + txt
                            j = j + 1
                        global starttime
                        endtime = time.time()
                        ent=time.time()
                        if max > 10:
                            print("%.2f" % (round(ent-sat, 2)))
                            #theLB.insert(END, "识别进度" + str(number) + " / " + str(max) + " 速率 : " + "%.2f" % (
                                    #( round(ent - sat, 2)) + "s"))
                        print("%.2f" % (round(ent - sat, 2)))
                        theLB.insert(END, "识别结束，总时间："+str(round(endtime - starttime, 2))+" 平均速度为"+str("%.2f" % ((max * 0.34*0.75) /round(endtime - starttime, 2))))
                        theLB.see(END)
                        #print("%.2f" % (((max / 50) * 0.34 * 0.75) / round(ent - sat, 2)))
                        #print("识别结束，总时间："+str(round(endtime - starttime, 0))+" 平均速度为"+str("%.2f" % ((max * 0.34*0.75) /round(endtime - starttime, 0))))
                        temp = base64.b64decode(ll).decode(encoding='gb18030')
                        with open("result/result.txt", "w+") as f:
                            f.write(temp)
                        if tkinter.messagebox.askyesno(title='识别成功', message='另存为'):
                            old_path = tk.filedialog.askdirectory()
                            shutil.copy("result/result.txt", old_path)
                        global flag
                        flag = 0
            return img
        def cc():
            cap = cv2.VideoCapture("INPUT_VIDEO.mp4")
            theLB.insert(END, "识别开始")
            print("2")
            global flag
            flag = 1
            global number
            global starttime
            global sat
            sat = time.time()
            starttime = time.time()
            number = 0
            while True:
                ret, frame = cap.read()
                if flag == 0:
                    break
                if ret == False:
                    break
                cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                img = Image.fromarray(cv2image)
                decodeDisplay(img)

            endtime = time.time()
            print("识别失败")
            print(round(endtime - starttime, 0))
        t = threading.Thread(target=cc)
        t.start()

    def video_demo(self, canvas, theLB):
        def decodeDisplay(img):
            global number
            barcodes = pyzbar.decode(img)
            for barcode in barcodes:
                barcodeData = barcode.data.decode("gb18030")
                try:
                    i = int(barcodeData[:8])
                except ValueError:
                    return img
                try:
                    max = int(barcodeData[8:16])
                except ValueError:
                    return img
                ll = ''

                if not os.path.exists("temp/result" + str(i) + ".txt"):
                    barcodeData = barcodeData[16:]
                    with open("temp/result" + str(i) + ".txt", "w+") as f:
                        f.write(barcodeData)
                        number = number + 1
                        global sat
                        if max >10:
                            if number % math.ceil(max/10) == 1:
                                sat = time.time()
                            elif number % math.ceil(max/10) == 0:
                                ent = time.time()
                                theLB.insert(END, "识别进度" + str(number) + " / " + str(max) + " 时间 : " + "%.2f" % (
                                        (round(ent - sat, 2)) + "s"))
                                theLB.see(END)
                    if number == max:
                        j = 1
                        while j <= number:
                            with open("temp/result" + str(j) + ".txt", "r+") as f:
                                txt = f.read()
                            ll = ll + txt
                            j = j + 1
                        global starttime
                        endtime = time.time()
                        ent = time.time()
                        if max >10:
                            theLB.insert(END,"识别进度" + str(number) + " / " + str(max) + " 速率 : " + "%.2f" % (
                                        ((max / 10) * 0.34*0.75) / round(ent - sat, 2)) + "KB/s")
                        theLB.insert(END, "识别结束，总时间：" + str(round(endtime - starttime, 0)) + " 平均速度为" + str(
                            "%.2f" % ((max * 0.34 * 0.75) / round(endtime - starttime, 0))))
                        theLB.see(END)

                        temp = base64.b64decode(ll).decode(encoding='gb18030')
                        with open("result/result.txt", "w+") as f:
                            f.write(temp)
                        if tkinter.messagebox.askyesno(title='识别成功', message='另存为'):
                            old_path = tk.filedialog.askdirectory()
                            shutil.copy("result/result.txt", old_path)
                        theLB.insert(END, "识别成功")
                        del_file()
            return img

        def cc():
            global number
            theLB.insert(END, "识别开始")
            number = 0
            capture = cv2.VideoCapture(1)
            while True:
                ret, frame = capture.read()  # 从摄像头读取照片
                cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
                img = Image.fromarray(cv2image)
                img = decodeDisplay(img)
                img = img.resize((500, 500), Image.ANTIALIAS)
                image_file = ImageTk.PhotoImage(img)
                canvas.create_image(0, 0, anchor='nw', image=image_file)
        t = threading.Thread(target=cc)
        t.start()

    def video_demo_load(self, canvas):
        def cc():
            cap = cv2.VideoCapture(1)  # 创建一个 VideoCapture 对象,打开摄像头
            flag = 1;
            # fourcc = cv2.VideoWriter_fourcc(*'XVID')#视频存储的格式
            # fourcc = cv2.VideoWriter_fourcc(*'MJPG')
            fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
            fps = cap.get(cv2.CAP_PROP_FPS)  # 帧率
            print(fps)
            # 视频的宽高
            size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
                    int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
            out = cv2.VideoWriter('INPUT_VIDEO.mp4', fourcc, fps, size)  # 视频存储
            starttime = time.time()
            while True:
                ret, frame = cap.read()  # 从摄像头读取照片
                out.write(frame)
                cv2.imshow("capture",frame)
                endtime = time.time()
                cv2.waitKey(1)
                if round(endtime - starttime, 2) > 120:
                    break
            cv2.destroyAllWindows()
        t = threading.Thread(target=cc)
        t.start()

    def desktop(self):
        del_file()
        self.face2_left.destroy()
        self.face2_mid.destroy()
        self.face2_right.destroy()
        self.face2_right_button.destroy()
        initface(self.master)

    def face1_transfer(self):
        del_file()
        self.face2_left.destroy()
        self.face2_mid.destroy()
        self.face2_right.destroy()
        self.face2_right_button.destroy()
        face1(self.master, 1)

if __name__ == '__main__':
    root = tk.Tk()
    basedesk(root)
    root.mainloop()
